# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
触发海拍客项目的接口
# post_hpk
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import copy
import hashlib
import json
from datetime import datetime


import requests

from interfacetest.baseset.hipac_api import API_HPK
from interfacetest.baseset.test_logger import Logger
from msydwork.config.config_hipac import w_url,pay_url
from pycacho.cachobase.deal_json import dict_to_json
from pycacho.cachobase.deal_time import str_to_timestamp
import threading

logger = Logger("post_hpk").get_log()

headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36',
            'content-Type': 'application/json'
        }

apply_info = {
    'requestId':''
}

partner_key = '3fda20b705aebf4aaf8097b309238ed8'
partner_no = '20200106002647'

merchantNo = '002647'
requestId = merchantNo + datetime.now().strftime('%Y%m%d%H%M%S')


# 外部接口加密
def get_sign(data):
    temp = json.dumps(data,ensure_ascii=False,sort_keys=True)           # 先排序str(temp).replace(' ','')
    encrypt = partner_key + partner_no + str(temp).replace(' ','')
    print('加密组装的数据：',encrypt)
    hl = hashlib.md5()
    hl.update(encrypt.encode(encoding='utf-8'))
    sign = hl.hexdigest()
    print('密钥：',sign)
    return sign

def apply_message(mer_no):
    fu_url = w_url + '/credit/v1/supplementalInfo'
    data = API_HPK['apply_message']
    data['requestId'] = 'CN'+ requestId
    data['merchantNo'] = mer_no
    data['partnerNo'] = partner_no
    data['firstOrderTime'] = 1577859934000
    data['lastOrderTime'] = 1578551134000
    print(data)
    sign = get_sign(data)
    headers.update({'sign':sign})
    req1 = requests.post(fu_url, json=data, headers=headers)
    data = req1.text
    logger.info("授信申请补件信息接口响应信息：%s", data)

def refund_apply():
    fu_url = w_url + '/refund/v1/apply'
    data = API_HPK['refund_apply']
    data['requestId'] = 'T002020111702'
    data['refundType'] = 1                # 0-全部退货,1-部分退货
    data['refundAmount'] = 1849.34
    data['loanNo'] = ''
    sign_data = copy.deepcopy(data)
    del sign_data['refundTime']        # 删除元素
    print(sign_data)
    sign = get_sign(sign_data)
    headers.update({'sign':sign})
    req1 = requests.post(fu_url, json=data, headers=headers)
    data = req1.json()
    print("退货申请接口响应信息：")
    dict_to_json(data)

def refund_query():
    fu_url = w_url + '/refund/v1/query'
    data = API_HPK['refund_query']
    data['loanNo'] = 'HIPAC202011161642451261820'
    sign = get_sign(data)
    headers.update({'sign':sign})
    req1 = requests.post(fu_url, json=data, headers=headers)
    data = req1.json()
    print("退货查询接口响应信息：")
    dict_to_json(data)

def loan_detail():
    fu_url = w_url + '/credit/v1/query/loanDetail'
    data = API_HPK['loan_detail']
    data['requestId'] = 'CN20200218002'
    data['loanNo'] = 'HIPAC202007101436517718I4z'
    sign = get_sign(data)
    headers.update({'sign':sign})
    req1 = requests.post(fu_url, json=data, headers=headers)
    data = req1.json()
    print("贷款详情查询接口响应信息：")
    dict_to_json(data)

def limit_query():
    fu_url = w_url + '/limit/v1/query'
    data = API_HPK['limit_query']
    data['requestId'] = 'CN20200218002'
    data['mchNo'] = merchantNo
    sign = get_sign(data)
    headers.update({'sign':sign})
    req1 = requests.post(fu_url, json=data, headers=headers)
    data = req1.json()
    print("商户额度查询接口响应信息：")
    dict_to_json(data)


# 内部接口加密
def web_sign(parm,loan_info):
    info = []
    parm.sort()
    encrypt = ''
    for key in parm:
        encrypt = encrypt + key + '=' + loan_info[key]  + '&'
    encrypt = encrypt + 'key='+ partner_key
    print('加密组装的数据：',encrypt)
    info.append(encrypt)
    hl = hashlib.md5()
    hl.update(encrypt.encode(encoding='utf-8'))
    sign = hl.hexdigest()
    print('密钥：',sign)
    info.append(sign)
    return info

def apply_loan(loan_date):
    loan_info = {
        "feeRepayFrom": "1",
        "loanAmount": '500.00',
        "loanDate": str(str_to_timestamp(loan_date)) + '000',
        "loanRemark": "zeng",
        "loanUse": "1",
        "merchantNo": merchantNo,
        "partnerNo": partner_no,
        "requestId":requestId ,             #   '2020111801'  requestId
        "queryUrl":''
    }
    parm = ['feeRepayFrom', 'loanAmount', 'loanDate', 'loanRemark', 'loanUse', 'merchantNo', 'partnerNo', 'requestId']
    fu_url = w_url + '/pay/applyLoan'
    data = copy.deepcopy(loan_info)
    info = web_sign(parm, loan_info)
    productNo = 'P0001'
    if productNo == 'P0001':
        loanPeriodType = 0
        loanPeriod = 30
    else:
        loanPeriodType = 1
        loanPeriod = 3
    data['productNo'] = productNo
    data['loanPeriod'] = loanPeriod
    data['loanPeriodType'] = loanPeriodType    # 借款期限类型，0-日，1-月，2-年
    data['password'] = '002647'
    data['sign'] = info[1]
    data['queryUrl'] = info[0] + '&sign=' + info[1]
    #print(data['queryUrl'])
    print('http://test.hpk.msxiaodai.com/html/OrderPayment.html?' + info[0].split('&key')[0]+'&sign=' + info[1])
    #req1 = requests.post(fu_url, json=data, headers=headers)
    #data = req1.json()
    print("用信申请提交接口响应信息：")
    #dict_to_json(data)

def account(type):
    if type == 'balance':
        fu_url = pay_url + '/pay/v1/temp/ws/balance?idNo=36242219881103431X&sysCode=PETHOME&productCode=PETHOME-H5'                     # 查询余额
    else:
        fu_url = pay_url + '/pay/v1/temp/ws/callback?subAcctNo=5845342722900687319&amt=15000000' # 充值100分
    req1 = requests.get(fu_url,headers=headers)
    data = req1.text
    print("网商银行接口响应信息：",data)
    #dict_to_json(data)

def temp():
    fu_url = w_url + '/v1/temp/initialRepayPlan'
    req1 = requests.get(fu_url, headers=headers)
    data = req1.json()
    print("个体商户额度激活：",data)

def batch_apply():
    threads = [threading.Thread(target=apply_loan(loan_date), args=(t,)) for t in range(1, 100)]  # 第212页
    for t in threads:
        t.start()

    for t in threads:
        t.join()


if __name__ == '__main__':
    loan_date = '2020-11-16 10:25:34'
    print(str(str_to_timestamp(loan_date)) + '000')
    #apply_loan(loan_date)
    #apply_message('002646')
    #refund_apply()
    #refund_query()
    #loan_detail()
    account('balance')         # balance-查询余额，
    #temp()
    #limit_query()






